﻿(function (window, undefine) {
    var geocoder;
    var map;
    var infowindow = new google.maps.InfoWindow();
    var marker;
    var markers = [];
    var latitude = null;
    var longitude = null;

    function initialize() {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(10.771918, 106.698347);
        var mapOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: 'roadmap'
        };
        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var pos = new google.maps.LatLng(position.coords.latitude,
                    position.coords.longitude);
                latitude = position.coords.latitude;
                longitude = position.coords.longitude;
            });
        }
        // This event listener will call addMarker() when the map is clicked.
        google.maps.event.addListener(map, 'click', function (event) {
            clearMarkers();
            markers = [];
            addMarker(event.latLng);
            latitude = event.latLng.k;
            longitude = event.latLng.B;
        });

        // Add a marker to the map and push to the array.
        function addMarker(location) {
            marker = new google.maps.Marker({
                position: location,
                map: map
            });
            markers.push(marker);
        }

        // Sets the map on all markers in the array.
        function setAllMap(map) {
            for (var i = 0; i < markers.length; i++) {
                markers[i].setMap(map);
            }
        }

        // Removes the markers from the map, but keeps them in the array.
        function clearMarkers() {
            setAllMap(null);
        }

    }

    function codeLatLng() {
        var latlng = new google.maps.LatLng(latitude, longitude);
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    map.setZoom(11);
                    marker = new google.maps.Marker({
                        position: latlng,
                        map: map
                    });
                    infowindow.setContent(results[1].formatted_address);
                    infowindow.open(map, marker);
                } else {
                    alert('No results found');
                }
            } else {
                alert('Geocoder failed due to: ' + status);
            }
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);

    $(document).ready(function () {
        $("#btnCurrenLocation").click(function () {
            codeLatLng();
        });
    });


})(window);